<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="备件编号">
          <el-input
            v-model="searchParam.spareCode"
            placeholder="请输入备件编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="备件名称">
          <el-input
            v-model="searchParam.spareNmae"
            placeholder="请输入备件名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="备件类型">
          <el-select
            v-model="searchParam.spareType"
            placeholder="请选择备件类型"
            clearable
          >
            <el-option
              v-for="item in useDictionary('SpareType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备件种类">
          <el-tree-select
            clearable
            @keyup.enter="search"
            placeholder="请选择备件种类"
            v-model="searchParam.spareKindId"
            :data="partTypeList"
            node-key="id"
            :props="{
              label: 'kindName',
              value: 'id',
              children: 'nodes',
            }"
            :render-after-expand="false"
            :check-strictly="true"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-tree-select
            clearable
            @keyup.enter="search"
            placeholder="请选择类型"
            v-model="searchParam.equipTypeId"
            :data="catalogList"
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            :render-after-expand="false"
            :check-strictly="true"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
        <el-button v-if="assetKind == 1" type="success" @click="excelBoxOpen"
          >导入
        </el-button>
        <el-dialog
          :key="uploadKey"
          :close-on-click-modal="false"
          title="备件数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/eam/eamsparepart/exportTemp',
                  '备件上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              备件上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              :loading="uploadLoading"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="备件编号"
          prop="spareCode"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="备件名称"
          prop="spareNmae"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="备件型号"
          prop="modelNo"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="备件类型"
          prop="spareType"
          min-width="120"
          align="center"
          sortable
        >
          <template #default="scope">
            {{ useDictionary("SpareType", scope.row.spareType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="设备种类"
          prop="assetTypeName"
          min-width="150"
          align="left"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.assetTypeCode }}{{ scope.row.assetTypeName ? "-" : ""
            }}{{ scope.row.assetTypeName }}
          </template>
        </el-table-column>
        <el-table-column
          label="备件种类"
          prop="spareKindName"
          min-width="120"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="设备"
          min-width="150"
          align="left"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            <span v-if="scope.row.details && scope.row.details.length">
              <span v-for="(item, index) in scope.row.details" :key="index">
                {{ item.assetName }}
                <span v-if="index != scope.row.details.length - 1">、</span>
              </span>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="制造商"
          prop="makerName"
          min-width="150"
          align="left"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.makerCode }}{{ scope.row.makerName ? "-" : ""
            }}{{ scope.row.makerName }}
          </template>
        </el-table-column>
        <el-table-column
          label="资产品牌"
          prop="brandName"
          min-width="150"
          align="left"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.brandCode }}{{ scope.row.brandName ? "-" : ""
            }}{{ scope.row.brandName }}
          </template>
        </el-table-column> -->
        <el-table-column
          label="备件价格"
          prop="sparePice"
          min-width="120"
          align="right"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="备件单位"
          prop="spareUnit"
          min-width="120"
          align="center"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="是否是关键备件"
          prop="isLinchpin"
          min-width="150"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag v-if="scope.row.isLinchpin == '1'" type="success"
              >是</el-tag
            >
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="是否易损备件属性"
          prop="isVulnerable"
          min-width="170"
          align="center"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            <el-tag v-if="scope.row.isVulnerable == '1'" type="success"
              >是</el-tag
            >
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="是否停用"
          prop="enabled"
          min-width="120"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
                ><i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
                ><i-ep-edit
              /></el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
                ><i-ep-delete />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <common-sparepart-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :assetKind="assetKind"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "CommonSparepart",
  inheritAttrs: false,
});
const props = defineProps({
  assetKind: {
    type: Number,
    default: null,
  },
});

const { assetKind } = toRefs(props);
// 请求参数
const requestApi = "/eam/eamsparepart/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  spareCode: "",
  spareNmae: "",
  spareType: "",
  equipTypeId: "",
  spareKindId: "",
  assetKind: assetKind.value,
};

const deleteParam = {
  api: "/eam/eamsparepart/delete",
  data: { assetKind: assetKind.value },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",

  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamsparepart/get/${id}`,
    method: "get",
    data: {
      assetKind: assetKind.value,
    },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开备件表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改备件";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增备件";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开备件表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "备件详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/eamsparepart/deleteItem/${id}`,
      method: "post",
      data: {
        assetKind: assetKind.value,
      },
    }).then((res) => {
      ElMessage.success("删除成功");
      search();
    });
  });
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: assetKind.value },
  }).then((res) => {
    console.log(res.data);

    catalogList.value = res.data;
  });
};

// 目录树
const partTypeList: any = ref([]);

// 获取内容树数据
const getPartTypeList = async () => {
  // 获取内容树
  await request({
    url: "/eam/parePartsType/getTree",
    method: "POST",
    data: { assetKind: assetKind.value },
  }).then((res) => {
    console.log(res.data);

    partTypeList.value = res.data;
  });
};

onMounted(() => {
  getCAtalogList();
  getPartTypeList();
});

// 导入excel
const uploadApi = "/eam/eamsparepart/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadKey = ref(Math.random());
const uploadFile = ref("");
const uploadLoading = ref(false);
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }
  uploadLoading.value = true;
  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  formdata.append("assetKind", assetKind.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadKey.value = Math.random();
      uploadLoading.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
      uploadLoading.value = false;
    });
}
</script>
